import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/returns/finalprocess/finalprocesslpnscreen.dart';
import 'package:opene/ui/returns/finalprocess/finalprocessrpsreen.dart';
import 'package:opene/ui/returns/finalprocess/finalprocesstrkscreen.dart';
import 'package:opene/ui/returns/returnsdialogscreen.dart';
import 'package:opene/ui/returns/returnsmodel.dart';
import 'package:opene/ui/tally/tallymodel.dart';
import 'package:opene/ui/tally/tallyskuscreen.dart';
import 'package:toast/toast.dart';

class FinalProcessScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FinalProcessScreenPage();
  }
}

class FinalProcessScreenPage extends StatefulWidget {
  @override
  _FinalProcessScreenPageState createState() => _FinalProcessScreenPageState();
}

class _FinalProcessScreenPageState extends BaseState<FinalProcessScreenPage> {
  final TextEditingController dateController = TextEditingController();
  final controller = ScrollController();

  int index = 0,
      position;
  FinalProcess finalProcess;
  List<ProcessingDTO> data = new List();
  List<FinalProcessDetail> tallyDetails = new List();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "FinalProcess";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration(milliseconds: 300), () {
      setState(() {
        getTallyContainerNo();
      });
    });
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 0, top: 10, right: 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.only(left: 15, top: 5, right: 15, bottom: 0),
            width: double.infinity,
            child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 40),
              child: TextField(
                controller: textEditingController,
                textInputAction: TextInputAction.search,
                onSubmitted: (String text) {
                  print('Searching for $text');
                  checkBatchNo(text);
                },
                // autofocus: true,
                decoration: InputDecoration(
                  suffixIcon: IconButton(
                    icon: Icon(
                      Icons.qr_code_scanner,
                      size: 25,
                      color: MyAppTheme.nearlyBlue,
                    ),
                    onPressed: () {
                      // requestPermissions();
                      // Utils.scanBarcode(context);
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        return ScanCode();
                      })).then((text) {
                        if (text == null) {
                          return;
                        }
                        print(text); //拿到扫描结果
                        checkBatchNo(text);
                      });
                    },
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: MyAppTheme.nearlyBlue,
                    ),
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点之外的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点时的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  hintText: "scan or input batch # / trk#",
                  filled: true,
                  fillColor: MyAppTheme.white,
                  //隐藏下划线
                  //border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                ),
                onChanged: (text) {
                  code = text;
                },
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 10, left: 15, right: 15),
            child: Row(
              children: [
                Expanded(
                  flex: 1, //设置权重
                  child: GestureDetector(
                    onTap: () {
                      // 请求焦点
                      FocusScope.of(context).requestFocus(FocusNode());
                      if (type == 1) {
                        return;
                      }
                      setState(() {
                        type = 1;
                        textEditingController.text = "";
                        data.clear();
                        setDataList();
                      });
                    },
                    child: Container(
                      padding: EdgeInsets.all(5),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: type == 1 ? MyAppTheme.nearlyBlue : MyAppTheme.white, // 背景颜色
                        borderRadius: BorderRadius.only(topLeft: Radius.circular(8.0), bottomLeft: Radius.circular(8.0)), // 圆角半径
                        border: Border.all(
                          color: MyAppTheme.nearlyBlue, // 边框颜色
                          width: 0.5, // 边框宽度
                        ),
                      ),
                      child: Text(
                        'Tallying',
                        style: type == 1 ? MyAppTheme.textWhite14 : MyAppTheme.text,
                      ), // 子控件，如果需要的话
                    ),
                  ),
                ),
                Expanded(
                  flex: 1, //设置权重
                  child: GestureDetector(
                    onTap: () {
                      // 请求焦点
                      FocusScope.of(context).requestFocus(FocusNode());
                      if (type == 2) {
                        return;
                      }
                      setState(() {
                        type = 2;
                        textEditingController.text = "";
                        data.clear();
                        setDataList();
                      });
                    },
                    child: Container(
                      padding: EdgeInsets.all(5),
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: type == 2 ? MyAppTheme.nearlyBlue : MyAppTheme.white, // 背景颜色
                        borderRadius: BorderRadius.only(topRight: Radius.circular(8.0), bottomRight: Radius.circular(8.0)), // 圆角半径
                        border: Border.all(
                          color: MyAppTheme.nearlyBlue, // 边框颜色
                          width: 0.5, // 边框宽度
                        ),
                      ),
                      child: Text(
                        'Completed',
                        style: type == 2 ? MyAppTheme.textWhite14 : MyAppTheme.text,
                      ), // 子控件，如果需要的话
                    ),
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            child: Container(
              margin: EdgeInsets.only(left: 15, right: 10, top: 10),
              child: setListView(),
            ),
          ),
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        ProcessingDTO tally = data[index];
        return Column(
          children: [
            Row(
              children: [
                Expanded(
                  flex: 2, //设置权重
                  child: GestureDetector(
                    onTap: () {
                      if (Utils.isEmpty(tally.lpn)) {
                        checkBatchNo(tally.batchNo);
                      } else {
                        returnCheckLpn(tally.batchNo, tally.lpn);
                      }
                    },
                    child: Text(
                      Utils.getStringisEmpty(tally.batchNo),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                    ),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    returnDetail(tally.batchNo);
                  },
                  child: Container(
                    margin: EdgeInsets.only(left: 5, right: 10),
                    child: Image.asset(
                      'assets/images/details.png',
                      width: 20,
                      height: 20,
                    ),
                  ),
                ),
              ],
            ),
            Divider(),
          ],
        );
      },
    );
  }

  @override
  void setNext() {
    ToastContext().init(context);
    if (Utils.isEmpty(textEditingController.text)) {
      Toast.show("Please enter batch #", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    checkBatchNo(textEditingController.text);
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
    });
  }

  void getTallyContainerNo() async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.processingAndComplete);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      setState(() {
        setState(() {
          finalProcess = FinalProcess.fromJson(baseResponse.data);
          setDataList();
        });
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void setDataList() {
    if (finalProcess == null) {
      return;
    }
    switch (type) {
      case 1:
        data = finalProcess.processing;
        break;
      case 2:
        data = finalProcess.complete;
        break;
    }
  }

  void checkBatchNo(String batchNo) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }

    Map<String, dynamic> map = new HashMap();
    map["batchNo"] = batchNo;
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.checkBatchNo, params: map);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      FinalProcessCheckBatch finalProcessCheckBatch = FinalProcessCheckBatch.fromJson(baseResponse.data);
      finalProcessTrk = finalProcessCheckBatch.returnCheckTrkRespVo;
      if (finalProcessTrk != null) {
        determineType();
        return;
      }

      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => FinalProcessLpnScreen( batchNo: batchNo, data: finalProcessCheckBatch.lpns)),
      ).then((value) =>
      {
        setState(() {
          textEditingController.text = "";
          hint = "";
        }),
        getTallyContainerNo()
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void returnDetail(String batchNo) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }

    Map<String, dynamic> map = new HashMap();
    map["batchNo"] = batchNo;
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.returnDetail, params: map);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      tallyDetails = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => FinalProcessDetail.fromJson(userJson)).toList());
      showDialog(
        context: context,
        builder: (context) => FinalProcessDetailDialog(batchNo: batchNo, tallyDetails: tallyDetails),
      );
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void returnCheckLpn(String batchNo, String lpn) async {
    try {
      // 显示加载中对话框
      LoadingIndicator.show(context);
    } catch (e) {
      e.toString();
    }

    Map<String, dynamic> map = new HashMap();
    map["batchNo"] = batchNo;
    map["lpn"] = lpn;
    BaseResponse baseResponse = await NetworkManager().request(context, Constants.returnCheckLpn, params: map);

    try {
      // 在需要的时候隐藏加载中对话框
      LoadingIndicator.hide();
    } catch (e) {
      e.toString();
    }

    if (baseResponse.status == 200) {
      List<FinalProcessLpn> finalProcessLpns = baseResponse.data == null ? null : (new List<dynamic>.from(baseResponse.data).map((userJson) => FinalProcessLpn.fromJson(userJson)).toList());
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => FinalProcessTrkScreen(oldIbLpn: lpn, batchNo: batchNo, finalProcessLpns: finalProcessLpns)),
      ).then((value) =>
      {
        setState(() {
          textEditingController.text = "";
          hint = "";
        }),
        getTallyContainerNo()
      });

    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }


  FinalProcessTrk finalProcessTrk;

  void determineType() {
    String hint = "";
    if (finalProcessTrk.quantity == null) {
      finalProcessTrk.quantity = 0;
    }
    if (finalProcessTrk.type == null) {
      finalProcessTrk.type = "";
    }

    //类型  D：指定销毁 D2：系统销毁 P：上架 R：返还客户  RP：重新拍照
    if (finalProcessTrk.type == "D") {
      //指定销毁
      hint = "please put it in a new inboundLPN,then putaway and destroy." + (finalProcessTrk.accountId != null ? (" LPN include ID：${finalProcessTrk.accountId}") : "") + "";
    }
    if (finalProcessTrk.type == "D2") {
      //系统销毁
      hint = "please put it in a new inboundLPN,then putaway and destroy." + (finalProcessTrk.accountId != null ? (" LPN include ID：${finalProcessTrk.accountId}") : "") + "";
    }
    if (finalProcessTrk.type == "P") {
      //上架
      hint = "please put it in a new inboundlpn ，and then putaway.";
    }
    if (finalProcessTrk.type == "R") {
      //返还客户
      hint = "Need to return it to customer，Please put it in inbound lpn. Waiting for customers to pick it" + (finalProcessTrk.accountId != null ? (" , LPN include ID：${finalProcessTrk.accountId}") : "") + ".";
    }
    if (finalProcessTrk.type == "RP") {
      //重新拍照
      hint = "please redo PreProcess for it！Keep it in the original inbound lpn";
    }


    showDialog(
      context: context,
      builder: (context) => FinalProcessTrkTypeDialog(processType: hint, finalProcessTrk: finalProcessTrk),
    ).then((value) =>
    {
      if (value != null && value)
        {
          if (finalProcessTrk.quantity > 1)
            {
              showDialog(
                context: context,
                builder: (context) => FinalProcessTrkTypeDialog(processType: hint, finalProcessTrk: finalProcessTrk),
              ).then((value2) =>
              {
                if (value2 != null && value2) {setNextData()}
              })
            }
          else
            {setNextData()}
        }
    });
  }

  void setNextData() {
    FinalProcessQr finalProcessQr = new FinalProcessQr();
    finalProcessQr.batchNo = finalProcessTrk.batchNo;
    finalProcessQr.oldIbLpn = finalProcessTrk.ibLpn;
    finalProcessQr.returnBatchDetailId = "${finalProcessTrk.id}";
    finalProcessQr.trackingCode = finalProcessTrk.trackingCode;
    finalProcessQr.type = finalProcessTrk.type;
    finalProcessQr.sku = finalProcessTrk.sku;
    finalProcessQr.newSku = finalProcessTrk.newSku;
    finalProcessQr.quantity = finalProcessTrk.quantity;
    finalProcessQr.account = finalProcessTrk.account;
    finalProcessQr.openLassSku = finalProcessTrk.openLassSku;
    finalProcessQr.accountId = finalProcessTrk.accountId;
    finalProcessQr.retape = finalProcessTrk.retape;

    if (finalProcessTrk.type == "RP") {
      //重新拍照
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => FinalProcessRPScreen(finalProcessQr: finalProcessQr)),
      ).then((value) {
        if (value == null) {} else if (value is bool) {
          Navigator.pop(context, true);
        } else if (value is FinalProcessReturn) {
          FinalProcessReturn finalProcessReturn = value;
          if (finalProcessReturn.trackingCode == null || finalProcessReturn.trackingCode.length == 0) {
            Navigator.pop(context, true);
          }
          setState(() {
            textEditingController.text = "";
            hint = "";
            finalProcessTrk = null;
            getTallyContainerNo();
          });
        }
      }).catchError((error) {
        // 错误处理
        print("An error occurred: $error");
      });
      return;
    }
  }
}
